package controllers

import (
	"bitbucket.org/alanwhen/infant-experience-class/enums"
	"bitbucket.org/alanwhen/infant-experience-class/models"
	"encoding/json"
	"github.com/astaxie/beego/orm"
	"golang.org/x/crypto/bcrypt"
	"strconv"
	"strings"
)

type SysUserController struct {
	BaseController
}

func (this *SysUserController) Prepare() {
	this.BaseController.Prepare()
	this.checkAuthor("DataGrid")
}

func (this *SysUserController) Index() {
	this.Data["pageTitle"] = "管理员管理"

	this.Data["showMoreQuery"] = true

	this.ActiveSidebarUrl()
	this.Data["canEdit"] = this.checkActionAuthor("SysUser", "Edit")
	this.Data["canDelete"] = this.checkActionAuthor("SysUser", "Delete")
	this.setTpl("sys_user/index")
}

func (this *SysUserController) DataGrid() {
	var params models.SysUserQueryParam
	json.Unmarshal(this.Ctx.Input.RequestBody, &params)

	data, total := models.SysUserPageList(&params)

	this.BootstrapJson(total, data)
}

func (this *SysUserController) Edit() {
	if this.Ctx.Request.Method == "POST" {
		this.Save()
	}

	Id, _ := this.GetInt(":id", 0)
	m := &models.SysUser{}
	var err error
	if Id > 0 {
		m, err = models.SysUserOne(Id)
		if err != nil {
			this.pageError("数据无效，请刷新后重试")
		}
		o := orm.NewOrm()
		o.LoadRelated(m, "RoleSysUserRel")
	} else {
		//添加用户时默认状态为启用
		m.Status = enums.Enabled
	}
	this.Data["m"] = m
	var roleIds []string
	for _, item := range m.RoleSysUserRel {
		roleIds = append(roleIds, strconv.Itoa(item.Role.Id))
	}
	this.Data["roles"] = strings.Join(roleIds, ",")
	this.setTpl("sys_user/edit", "shared/layout_pullbox", "footer")
}

func (this *SysUserController) Save() {
	m := models.SysUser{}
	o := orm.NewOrm()
	var err error
	if err = this.ParseForm(&m); err != nil {
		this.jsonResult(enums.JRCodeFailed, "获取数据失败", m.Id)
	}

	if _, err := o.QueryTable(models.RoleSysUserRelTBName()).Filter("sys_user_id", m.Id).Delete(); err != nil {
		this.jsonResult(enums.JRCodeFailed, "删除历史关系失败", "")
	}

	if m.Id == 0 {
		hash, err := bcrypt.GenerateFromPassword([]byte(m.Password), bcrypt.DefaultCost)
		if err != nil {
			this.jsonResult(enums.JRCodeFailed, "生成密码失败", "")
		}
		m.Password = string(hash)
		if _, err := o.Insert(&m); err != nil {
			this.jsonResult(enums.JRCodeFailed, "添加失败", m.Id)
		}
	} else {
		if oM, err := models.SysUserOne(m.Id); err != nil {
			this.jsonResult(enums.JRCodeFailed, "数据无效", m.Id)
		} else {
			m.Password = strings.TrimSpace(m.Password)
			if len(m.Password) == 0 {
				m.Password = oM.Password
			} else {
				hash, err := bcrypt.GenerateFromPassword([]byte(m.Password), bcrypt.DefaultCost)
				if err != nil {
					this.jsonResult(enums.JRCodeFailed, "密码生成错误，编辑失败", m.Id)
				}
				m.Password = string(hash)
				m.Avatar = oM.Avatar
			}
			if _, err := o.Update(&m); err != nil {
				this.jsonResult(enums.JRCodeFailed, "编辑失败", m.Id)
			}
		}
	}

	//添加关系
	var relations []models.RoleSysUserRel
	for _, roleId := range m.RoleIds {
		r := models.Role{Id: roleId}
		relation := models.RoleSysUserRel{SysUser: &m, Role: &r}
		relations = append(relations, relation)
	}
	if len(relations) > 0 {
		if _, err := o.InsertMulti(len(relations), relations); err == nil {
			this.jsonResult(enums.JRCodeSuccess, "保存成功", m.Id)
		} else {
			this.jsonResult(enums.JRCodeFailed, "保存失败", m.Id)
		}
	} else {
		this.jsonResult(enums.JRCodeSuccess, "保存成功", m.Id)
	}
}
